<template>
  <div class="login">
    <!-- 顶部栏 -->
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        name="mobile"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="[
          { required: true, message: '验证码没有写哦!' },
          { pattern: /^\d{6}$/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button 
        round 
        block
        :disabled="isLoading" 
        :loading="isLoading"
        loading-text="登录中..."
        loading-type="spinner"
        type="info" 
        native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
//导入接口
import { getLogin } from './user.js'
//导入token.js
import {saveToken} from '@/utils/token.js'

export default {
  name: 'login',
  data () {
    return {
      mobile: '',
      code: '',
      isLoading:false//登录按钮禁用状态
    }
  },
  methods: {
    onSubmit (values) {
      /* 
        1.values是一个对象,存储表单中的数据
        2.values中对象的属性名是：表单的name值  属性值是：表单value
        3.onSubmit方法触发前提是要通过验证
         */
      //   console.log('submit', values);
      //1.设置登录按钮禁用状态
          this.isLoading=true
  //2.调用登录接口
    setTimeout(()=>{
        getLogin(values).then(res => {
        console.log(res)
        saveToken(res.data.data)
        this.$toast.success('登录成功')
          this.$router.push('/')
      }).catch(err=>{
        this.$toast.fail('账号或验证码错误')

      }).then(()=>{
        setTimeout(()=>{
          this.isLoading=false
        },700)
      })
    },500)
    }
  }
}
</script>

<style lang="less">
.van-nav-bar__content {
  background-color: #0098fa;
  .van-nav-bar__left {
    .van-icon-arrow-left {
      color: #fff;
    }
    .van-nav-bar__text {
      color: #fff;
    }
  }
  .van-nav-bar__title {
    color: #fff;
  }
}
</style>
